<script setup>
import {
  auditStudentInternshipMaterialApi,
  checkStudentWeeklyApi,
  getStudentByClassApi,
  getStudentInternshipMaterialApi,
  getStudentWeeklyByCounselorApi,
  uploadStudentInternshipMaterialsApi
} from '@/api/job'
import Form from '@/components/User/Form.vue'
import Pagization from '@/components/common/pagization.vue'
import Table from '@/components/practice/table.vue'
import { showStatusMessage } from '@/utils/common/showMessage'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import router from '@/router'
import { utils, writeFileXLSX, read } from 'xlsx'
import { dayFormat } from '@/utils/common/dayjs'

const userStore = useUserStore()
// **********************筛选表**********************
const formData = ref({
  account: '',
  class: '',
  name: ''
})
const formModel = [
  {
    prop: 'account',
    label: '账号',
    type: 'input'
  },
  {
    prop: 'class',
    label: '班级',
    type: 'input'
  },
  {
    prop: 'name',
    label: '姓名',
    type: 'input'
  }
]
const btnOpt = [
  {
    name: '查询',
    btnType: '',
    prop: 'query'
  },
  {
    name: '重置',
    btnType: 'info',
    prop: 'reset'
  },
  {
    name: '导出',
    btnType: 'primary',
    prop: 'output'
  }
] /**
 * 点击重置按钮
 */
function reset() {
  getTableData()
  pagizationRef.value.reset()
  selectFormRef.value.reset()
}
//******************* */ 分页先关的***************
const pagizationRef = ref(null)
const selectFormRef = ref(null)
const pagizationToatl = ref(null)
/**
 * 获取表格数据
 */
async function getTableData(data) {
  let params = null
  if (userStore.userInfo.identity === '管理员') {
    params = {
      ...data
    }
  } else {
    params = {
      studentClass: userStore.userInfo.class,
      ...data
    }
  }
  const res = await getStudentWeeklyByCounselorApi(params)

  tableData.value = res.data?.map((item) => {
    return {
      ...item
    }
  })
  pagizationToatl.value = res.total
}

/**
 * 表单按钮点击事件
 * @param type 操作类型
 * @param data 表单数据
 */
function handleForm(type, data) {
  // console.log(type, data)
  switch (type) {
    case 'query':
      query(data)
      break
    case 'output':
      exportToExcel()
      break
    case 'reset':
      reset(data)
      break
    case 'import':
      handleUpload(data)
      break
    case 'submit':
      handleSubmit(data)
      break
    default:
      break
  }
}

/**
 * 表单查询事件
 * @param {Object} data 查询条件
 */
const queryData = ref(null)
async function query(data) {
  console.log(data)

  getTableData(data)
}

// 列表数据
const tableData = ref([])
const columns = [
  {
    prop: 'type',
    label: '实习类型'
  },
  {
    prop: 'weekly',
    label: '第几周'
  },
  {
    prop: 'weeklyNum',
    label: '需提交次数'
  },
  {
    prop: 'name',
    label: '姓名'
  },
  {
    prop: 'class',
    label: '班级'
  },
  {
    prop: 'create_time',
    label: '上传时间'
  },
  {
    prop: 'status',
    label: '状态',
    display: 'tag'
  }
]
const options = [
  {
    label: '查看',
    type: 'primary',
    prop: 'viewWeekly'
  },
  {
    label: '驳回',
    type: 'danger',
    prop: 'noprocess'
  },
  {
    label: '通过',
    type: 'success',
    prop: 'processs'
  }
]
const docPreview = ref('')
const dialogViewVisible = ref(false)
// 下载材料
async function handletTableMaterial(data) {
  const fileNamePop = data.material.split('/').pop().split('.').pop()
  const res = await axios({
    method: 'get',
    url: data.material,
    responseType: 'blob'
  })

  const blob = new Blob([res.data], {
    type: 'application/octet-stream' // 通用文件流类型
  })
  const fileName = `${data.desc}.${fileNamePop}`
  const a = document.createElement('a')
  const url = URL || window.webkitURL
  const href = url.createObjectURL(blob)
  a.style.display = 'none'
  a.href = href
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  url.revokeObjectURL(href)
}
function handleDialogViewClose() {
  docPreview.value = ''
}

// 材料审核
async function handletTableProcess(data) {
  console.log(data)

  const res = await checkStudentWeeklyApi({
    id: data.id,
    status: 2,
    weekly: data.weekly,
    account: data.account
  })
  showStatusMessage(res)
  getTableData()
}
const ruleFormRef = ref(null)
const ruleForm = ref({
  rejectReason: ''
})
const descRules = {
  rejectReason: [{ required: true, message: '请输入驳回原因', trigger: 'blur' }]
}
const rejectId = ref(null)
function handleReject() {
  ruleFormRef.value.validate(async (valid) => {
    if (!valid) return

    const res = await checkStudentWeeklyApi({
      id: rejectId.value,
      status: 1,
      desc: ruleForm.value.rejectReason
    })
    showStatusMessage(res)
    getTableData()
    rejectId.value = null
    ruleForm.value.rejectReason = ''
    dialogViewVisible.value = false
  })
}
async function handletTableNoProcess(data) {
  dialogViewVisible.value = true
  rejectId.value = data.id
}

// 查看学生实习周记
function handletTableViewWeekly(data) {
  console.log(data)
  router.push({
    name: 'weeklyJournalDetail',
    state: {
      data: JSON.stringify(data),
      type: 'weeklyDetail'
    }
  })
}

/**
 * 表格的操作事件
 * @param {Object} data  操作行的数据
 * @param {String} type 操作类型-'edit'-'delete'
 */
function handleTable(data, type) {
  // console.log(data, type)
  switch (type) {
    case 'material':
      handletTableMaterial(data)
      break
    case 'submitMaterial':
      handletTableSubmitMaterial(data)
      break
    case 'processs':
      handletTableProcess(data)
      break
    case 'noprocess':
      handletTableNoProcess(data)
      break
    case 'viewWeekly':
      handletTableViewWeekly(data)
      break

    default:
      break
  }
}
// 分页器条数发生变化
function handleSizeChange(val) {
  const data = selectFormRef.value.getValue()
  console.log('条数发生变化')
  getTableData({ size: val, ...data })
  pagizationRef.value.reset()
}
// 分页器页数发生变化
function handleCurrentChange(page, size) {
  const data = selectFormRef.value.getValue()
  console.log('页数发生变化')
  getTableData({ page, size, ...data })
}

// 弹窗显示
const dialogTableVisible = ref(false)
const FormJobData = ref({
  studentMaterialDesc: '',
  studentMaterial: ''
})
const formJobOpt = [
  {
    prop: 'studentMaterialDesc',
    label: '实现材料名称',
    type: 'input',
    disabled: true
  },
  {
    prop: 'studentMaterial',
    label: '上传材料',
    type: 'studentMaterial'
  }
]
const btnJobOpt = [
  {
    name: '取消',
    btnType: 'info',
    prop: 'cancel'
  },
  {
    name: '提交',
    btnType: 'primary',
    prop: 'submit'
  }
]

const formJobRef = ref(null)
//dialog关闭前的回调
function handleDialogClose() {
  formJobRef.value.reset()
}

async function handleSubmit(data) {
  console.log(data)
  let info = {
    studentAccount: userStore.userInfo.account,
    studentClass: userStore.userInfo.class,
    studentMaterial: data.studentMaterial,
    studentMaterialDesc: data.studentMaterialDesc
  }

  const res = await uploadStudentInternshipMaterialsApi(info)
  showStatusMessage(res)
  dialogTableVisible.value = false
  getTableData()
  handleDialogClose()
}
const classList = ref(userStore.userInfo.class)
const activeClass = ref(userStore.userInfo.class[0])
function unSubmitClass() {
  // return classList.value.filter((item) => item !== activeClass.value)
}
console.log(classList.value)
function handleClassClick(val) {
  getTableData({ studentClass: activeClass.value })
}
getTableData({ studentClass: activeClass.value })

async function exportToExcel() {
  // 表头中文字段value
  const tableHeaderValues = ['账号', '姓名', '班级', '第几周', '需提交次数', '实习类型']
  // 以excel表格的顺序调整后端数据
  const sheetData = tableData.value.map((item, index) => {
    let obj = {}
    obj = {
      studentAccount: item.account,
      studentName: item.name,
      studentClass: item.class,
      materialName: item.weekly,
      weeklyNum: item.weeklyNum,
      internshipType: item.type
    }
    return obj
  })

  // 创建一个工作表
  const worksheet = utils.json_to_sheet(sheetData)
  // 创建一个新的工作簿
  const workbook = utils.book_new()
  // 把工作表添加到工作簿
  utils.book_append_sheet(workbook, worksheet, 'Data')
  // 改写表头
  utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
  writeFileXLSX(workbook, `${dayFormat(new Date())}${activeClass.value}提交导出数据.xlsx`)

  unsubmit()
}
async function unsubmit() {
  // 1.获取负责班级的学生
  const { data: studentArr } = await getStudentByClassApi({ class: activeClass.value })
  const {data:needValue} = await getStudentInternshipMaterialApi({ class: activeClass.value })
  console.log(needValue);
  
  // 筛选出未提交周记的学生
  const unsubmittedStudents = studentArr.map(student => {
    // 获取该学生已提交的周记
    const submittedWeeklies = tableData.value.filter(weekly => weekly.account === student.account)
    
    // 找出未提交的实习类型
    const unsubmittedTypes = needValue.filter(need => {
      // 检查该实习类型是否已提交
      return !submittedWeeklies.some(weekly => weekly.type === need.type)
    }).map(need => need.type)
    
    return {
      account: student.account,
      name: student.name,
      class: student.class,
      unsubmittedTypes: unsubmittedTypes // 未提交的实习类型列表
    }
  }).filter(student => student.unsubmittedTypes.length > 0) // 只保留有未提交实习类型的学生

  const tableHeaderValues2 = ['账号', '姓名', '班级', '未提交的实习类型']

  const sheetData2 = unsubmittedStudents.map((item) => {
    return {
      account: item.account,
      name: item.name,
      class: item.class,
      unsubmittedTypes: item.unsubmittedTypes.join(', ') // 将未提交的实习类型数组转换为字符串
    }
  })

  // 创建第二个工作表
  const worksheet2 = utils.json_to_sheet(sheetData2)
  // 创建一个新的工作簿
  const workbook2 = utils.book_new()
  // 把工作表添加到工作簿
  utils.book_append_sheet(workbook2, worksheet2, 'Data')
  // 改写表头
  utils.sheet_add_aoa(worksheet2, [tableHeaderValues2], { origin: 'A1' })
  writeFileXLSX(workbook2, `${dayFormat(new Date())}${activeClass.value}未提交导出数据.xlsx`)
}
</script>

<template>
  <div class="license-wrapper">
    <div class="user-content">
      <Form
        :data="formData"
        :formOpt="formModel"
        :btnOpt="btnOpt"
        @handleForm="handleForm"
        ref="selectFormRef"
      ></Form>
      <!-- 班级 -->
      <el-tabs v-model="activeClass" type="card" class="demo-tabs" @tab-click="handleClassClick">
        <el-tab-pane v-for="item in classList" :key="item" :label="item" :name="item"></el-tab-pane>
      </el-tabs>
      <!-- 表格 -->
      <Table
        :tableData="tableData"
        :columns="columns"
        :options="options"
        @handleTable="handleTable"
      >
        <template #firstColumn>
          <el-table-column type="index" label="编号" width="100" align="center" />
        </template>
      </Table>
      <!-- 分页 -->
      <Pagization
        ref="pagizationRef"
        :total="pagizationToatl"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      ></Pagization>

      <iframe :src="docPreview" frameborder="0" style="display: none"></iframe>
      <!-- 文件预览 -->
      <el-dialog v-model="dialogViewVisible" top="25vh" width="420" @close="handleDialogViewClose">
        <!--表单 -->
        <el-form :model="ruleForm" ref="ruleFormRef" :rules="descRules">
          <el-form-item label="驳回原因" prop="rejectReason">
            <el-input
              type="textarea"
              v-model="ruleForm.rejectReason"
              :rows="2"
              placeholder="请输入驳回原因"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="dialogViewVisible = false">取消</el-button>
            <el-button type="primary" @click="handleReject">确认</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.license-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: start;

  .user-content {
    width: 100%;
    padding: 10px 50px;
    text-align: left;
    overflow: auto;

    .demo-drawer {
      .drawer-content {
        .content-list {
          margin-bottom: 28px;

          span {
            font-size: 20px;
            font-weight: bold;
          }
        }
      }
    }
    .weekly-drawer {
      .item {
        .item-title {
          font-size: 20px;
          font-weight: bold;
          margin-bottom: 10px;
        }
        .item-content {
          font-style: 17px;
          font-family: 'PMZDR';
          text-indent: 2rem;
        }
      }
    }
  }
}
</style>
